package com.superb.allocation.service.oss.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.*;
import com.superb.allocation.service.oss.BucketService;
import com.superb.common.utils.HeardersUtils;

import java.util.List;

/**
 * @Author: ajie
 * @CreateTime: 2024-07-04 16:23
 */
public class BucketServiceImpl implements BucketService {

    private final OSS client;
    private final String bucket;
    private final CannedAccessControlList controlList;

    public BucketServiceImpl(OSS client) {
        this.client = client;
        this.bucket = HeardersUtils.getHeader("bucket", () -> "zlgyl");
        String auth = HeardersUtils.getHeader("auth", () -> "false");
        this.controlList = "false".equals(auth) ? CannedAccessControlList.Private : CannedAccessControlList.PublicRead;
    }
    
    private boolean bucketExists() {
        return this.client.doesBucketExist(this.bucket);
    }

    @Override
    public void createBucket() {
        if (!this.bucketExists()) {
            CreateBucketRequest request = new CreateBucketRequest(this.bucket);
            request.setCannedACL(controlList);
            this.client.createBucket(request);
        }
    }

    @Override
    public List<Bucket> buckets() {
        return this.client.listBuckets();
    }

    @Override
    public BucketInfo bucketInfo() {
        return this.client.getBucketInfo(this.bucket);
    }

    @Override
    public BucketStat bucketStat() {
        return this.client.getBucketStat(this.bucket);
    }

    @Override
    public boolean deleteBucket() {
        VoidResult result = this.client.deleteBucket(this.bucket);
        ResponseMessage response = result.getResponse();
        return response.isSuccessful();
    }
}
